Common subexpression elimination

In computer science, common subexpression elimination (CSE) is a compiler optimization that searches for instances of identical expressions (i.e., they all evaluate to the same value), and analyses whether it is worthwhile replacing them with a single variable holding the computed value.

Contents

Example

In the following code:

a = b * c + g;
d = b * c * d;

it may be worth transforming the code to:

tmp = b * c;
a = tmp + g;
d = tmp * d;

if the time cost of storing and retrieving "tmp" outweighs the cost of calculating "b * c" an extra time.

Principle

The possibility to perform CSE is based on available expression analysis (a data flow analysis). An expression b*c is availabe at a point p in a program if:

The cost/benefit analysis performed by an optimizer will calculate whether the cost of the store to tmp is less than the cost of the multiplication; in practice other factors such as which values are held in which registers are also significant.

Compiler writers distinguish two kinds of CSE:

Both kinds rely on data flow analysis of which expressions are available at which points in a program.

Benefits

The benefits of performing CSE are great enough that it is a commonly used optimization.

In simple cases like in the example above, programmers may manually eliminate the duplicate expressions while writing the code. The greatest source of CSEs are intermediate code sequences generated by the compiler, such as for array indexing calculations, where it is not possible for the developer to manually intervene. In some cases language features may create many duplicate expressions. For instance, C macros, where macro expansions may result in common subexpressions not apparent in the original source code.

Compilers need to be judicious about the number of temporaries created to hold values. An excessive number of temporary values creates register pressure possibly resulting in spilling registers to memory, which may take longer than simply recomputing an arithmetic result when it is needed.

See also

References